<template>
    <div class="app-container dialog-w80">
        <div class="customContainer">
            <!-- 搜索头 -->
            <el-form :inline="true" :model="formInline" class="demo-form-inline" size="small">
                <el-form-item>
                    <el-date-picker v-model="pickerDate" value-format="yyyy.MM.dd" type="daterange" align="right"
                        unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                        :picker-options="pickerOptions"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-select filterable placeholder="选择门店" v-model="formInline.store_id" style="width:200px;">
                        <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="formInline.order_no" placeholder="订单查询"></el-input>
                </el-form-item>
                <el-form-item>
                    <dj-button size="small" @search="searchClick" />
                </el-form-item>
            </el-form>
            <!-- 列表 -->
            <el-table highlight-current-row :data="list" v-loading.body="listLoading" border size="small"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="36"></el-table-column>
                <el-table-column align="center" label='序号' width="50">
                    <template slot-scope="scope">
                        <span class="indexColor">{{scope.$index+1+(currentPage-1)*20}}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='订单状态'>
                    <template slot-scope="scope">
                        <span v-if="scope.row.status==0">待审核</span>
                        <span v-if="scope.row.status==1">待出货</span>
                        <span v-if="scope.row.status==2">待收货</span>
                        <span v-if="scope.row.status==3">部分收货</span>
                        <span v-if="scope.row.status==4">订单完结</span>
                        <span v-if="scope.row.status==5">收货完成</span>
                        <span v-if="scope.row.status==6">订单取消</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="订单编号">
                    <template slot-scope="scope">
                        <el-button
                            @click="get_order_info(scope.row.id,scope.$index,scope.row.status,scope.row.store_out_name,scope.row.store_in_name)"
                            type="text" size="small">{{scope.row.order_no}}</el-button>
                    </template>
                </el-table-column>
                <el-table-column align="center" label='礼品调出仓' prop="house_out_name"></el-table-column>
                <el-table-column align="center" label="礼品调入仓" prop="house_in_name">
                </el-table-column>
                <el-table-column align="center" label="下单时间" prop="create_time">
                </el-table-column>
                <el-table-column align="center" label='操作' prop="">
                    <template slot-scope="scope">
                        开
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 弹框-->
        <el-dialog :close-on-click-modal="false" class="dialog_table" :title="dialogTitle"
            :visible.sync="detail_dialog">
            <div class="dialogInContainer" v-loading="dialogLoading">
                <div style="position:relative;top:-20px">调出仓：{{out_name}}&#x3000;&#x3000;调入仓：{{in_name}}</div>
                <el-table highlight-current-row :data="infolist" v-loading.body="listLoading" border size="small"
                    @selection-change="detailSelection" :key="dialogTitle">
                    <el-table-column v-if="dialogTitle=='店外礼品调拨入库'&&!isDisabled" type="selection" width="36"></el-table-column>
                    <el-table-column align="center" label='序号' width="50">
                        <template slot-scope="scope">
                            <span class="indexColor">{{scope.$index+1}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="图片" width="70">
                        <template slot-scope="scope">
                            <img :src="scope.row.thumb" width="50" height="50" alt="">
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="礼品名称" prop="gift_name"></el-table-column>
                    <el-table-column align="center" label="新礼品编号" prop="gift_id"></el-table-column>
                    <el-table-column align="center" label="神采礼品编号" prop="no_obsolete"></el-table-column>
                    <el-table-column align="center" label="箱规" prop="box_num"></el-table-column>
                    <el-table-column align="center" label="尺寸">
                        <template slot-scope="scope">
                            {{scope.row.size?scope.row.size:'-'}}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="三级分类" prop="type_name"></el-table-column>
                    <el-table-column align="center" label="成本价" prop="money_cost"></el-table-column>
                    <el-table-column align="center" label="订单数" prop="order_num"></el-table-column>
                    <el-table-column v-if="stat==2||stat==3" align="center" label="累计到货数" prop="arrive_num">
                    </el-table-column>
                    <el-table-column v-if="stat==2||stat==3" align="center" label="本次到货数">
                        <template slot-scope="scope">
                            <el-input type="number" onmousewheel="return false;" v-model="scope.row.now_arrive_num"
                                :disabled="isDisabled||scope.row.all_arrive" placeholder="数量"></el-input>
                        </template>
                    </el-table-column>
                </el-table>
                <!-- 自定义底部 -->
                <div class="bottom_box">
                    <el-button v-if="infoSelection.length>0 && !isDisabled" :disabled="isDisabled" size="small"
                        type="primary" @click="allArriveClick()">无差异到货</el-button>
                    <el-button v-if="infoSelection.length>0 && !isDisabled" :disabled="isDisabled" size="small"
                        type="primary" @click="resetClick()">重置</el-button>
                    <el-button v-if="stat==1" :disabled="isDisabled" class="pull-right" size="small" type="primary"
                        @click="outsaveClick()">确认出库</el-button>
                    <el-button v-if="stat==2" :disabled="isDisabled" class="pull-right" size="small" type="primary"
                        @click="insaveClick()">确认入库</el-button>
                    <p class="pull-right" style="line-height:5px">订单总数:{{totalOrder}} 　合计:{{totalPrice|keepTwoNum}} 　
                    </p>
                </div>
            </div>
        </el-dialog>
        <!-- 自定义底部 -->
        <div class="bottom_box">
            <el-pagination class="pull-left" background @current-change="handleCurrentChange"
                :current-page.sync="currentPage" :page-size="20" layout="prev, pager, next, jumper"
                :total="totalDataNumber">
            </el-pagination>
            <el-button :disabled="exportForm.length==0" class="pull-right" type="primary" size="small"
                @click="exportClick()" :loading="exportLoading">调拨单导出<count-down ref="cd"/></el-button>
        </div>
    </div>
</template>

<script>
    import {
        getStoreList,
        getList,
        getPage,
        getinfoPage,
        getinfoList,
        getExport,
        outsave,
        insave
    } from "@/api/storage_control/look_out_allocating";
    import { pickerOptionsF, pickerDateF, optionMaxTime } from '@/utils';
    export default {
        data() {
            return {
                exportLoading: false,
                dialogLoading: false,
                list: null,
                infoSelection:[],
                editId: '',
                out_name: '',
                in_name: '',
                listLoading: false,
                currentPage: 1,
                totalDataNumber: 1,
                storeList: null,
                storageList: '',
                formInline: {
                    store_id: '',
                    order_no: '',
                    start_time: "",
                    end_time: "",
                    position: "in",
                    status: 100
                },
                pickerOptions: pickerOptionsF(),
                pickerDate: pickerDateF(),
                detail_dialog: false,
                totalOrder: "0",
                totalPrice: "0",
                infolist: [],
                exportForm: [],
                isDisabled: false,
                stat: '',
                dialogTitle: '',
                saveForm: {
                    order_id: this.editId,
                    order: []
                },
            };
        },
        beforeRouteEnter(to, from, next) {
            next((vm) => {//当进入组件之前，执行 beforRouteEnter 路由钩子函数 ,//参数vm就是当前组件的实例。
                if (!vm.storeList) {
                    vm.getStore();
                }
            })
        },
        methods: {
            detailSelection(val) {
                this.infoSelection = val;
            },
            resetClick() {
                this.infoSelection.forEach(val1 => {
                    this.infolist.forEach(val2 => {
                        if (val1.id == val2.id) {
                            val2.now_arrive_num = '';
                        }
                    });
                });
            },
            allArriveClick() {
                this.infoSelection.forEach(val1 => {
                    this.infolist.forEach(val2 => {
                        if (val1.id == val2.id) {
                            val2.now_arrive_num = 0;
                            val2.now_arrive_num = val2.order_num * 1 - val2.arrive_num * 1 == 0 ? '' : val2.order_num * 1 - val2.arrive_num * 1;
                        }
                    });
                });
            },
            outsaveClick() {
                const that = this;
                that.saveForm.order = [];
                this.infolist.forEach(function (val, index) {
                    if (val.order_num == '') {
                        return;
                    } else {
                        that.saveForm.order.push({ look_money: val.money_cost, gift_id: val.gift_id, out_num: val.order_num })
                    }
                });
                if (this.saveForm.order.length == this.infolist.length) {
                    this.$confirm('此操作提交, 是否继续?', '提示', { type: 'warning' }).then(() => {
                        outsave(this.saveForm).then(response => {
                            this.$message({
                                type: response.code == 1 ? 'success' : 'error',
                                message: response.message
                            });
                            if (response.code == 1) {
                                this.detail_dialog = false;
                                this.handleCurrentChange(this.currentPage)
                            }
                        });
                    });
                } else {
                    that.$message({ type: 'error', message: '请将所有信息填写完整!' })
                    return;
                }
            },
            insaveClick() {
                this.saveForm.order = [];
                let ok = true;
                // 过滤掉全部到货的数组
                let new_infolist = this.infolist.filter(function (item) { return item.order_num != item.arrive_num });
                this.infolist.forEach((val, index) => {
                    if (val.now_arrive_num > (val.order_num - val.arrive_num)) {
                        ok = false
                        return false;
                    }
                    if ((val.now_arrive_num != null && val.now_arrive_num * 1 >= 0 && val.now_arrive_num != '' && /^\d+$/.test(val.now_arrive_num)) || val.all_arrive) {
                        this.saveForm.order.push({ look_money: val.money_cost, gift_id: val.gift_id, arrive_num: val.now_arrive_num * 1 })
                    }
                });
                if (!ok) {
                    this.$message({ type: 'error', message: '到货数不能大于订单数!' })
                    return;
                }
                if (this.saveForm.order.length == this.infolist.length) {
                    this.$confirm('此操作提交, 是否继续?', '提示', { type: 'warning' }).then(() => {
                        insave(this.saveForm).then(response => {
                            this.$message({
                                type: response.code == 1 ? 'success' : 'error',
                                message: response.message
                            });
                            if (response.code == 1) {
                                this.detail_dialog = false;
                                this.handleCurrentChange(this.currentPage)
                            }
                        });
                    });
                } else {
                    this.$message({ type: 'error', message: '请将所有信息填写完整，到货数只能为整数!' })
                    return;
                }
            },
            // 选择
            handleSelectionChange(val) {
                this.exportForm = val;
            },
            // 搜索
            searchClick() {
                optionMaxTime(this.pickerDate).then(() => {//最大可选择时间区间
                    this.formInline.start_time = this.pickerDate ? this.pickerDate[0] : '';
                    this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : '';
                    this.fetchData();
                });
            },
            // 获取门店列表
            getStore() {
                getStoreList(this.formInline).then(response => {
                    this.storeList = response;
                    let data = response.filter(res => 
                        res.id == this.$store.getters.optionId
                    )
                    if(data.length>0){
                        this.formInline.store_id = data[0].id;
                    }
                })
            },
            // 导出
            exportClick() {
                const idArr = []
                this.exportForm.forEach(function (val, index) {
                    idArr.push(val.id)
                });
                getExport({ type: 2, order_id: idArr.join(',') })
                this.exportLoading = true;
                this.$refs.cd.countDownF(30).then(() => {
                    this.exportLoading = false;
                });
            },
            // 打开订单详情
            get_order_info(id, index, status, store_out_name, store_in_name) {
                this.dialogLoading = true;
                this.out_name = store_out_name;
                this.in_name = store_in_name;
                this.saveForm.order_id = id;
                this.stat = '';
                this.isDisabled = true;
                this.storeList.forEach( (val, index)=> {
                    if (status == 1 && val.name == store_out_name) {
                        this.stat = 1;
                        this.isDisabled = false;
                    } else if ((status == 2 && val.name == store_in_name) || (status == 3 && val.name == store_in_name)) {
                        this.stat = 2;
                        this.isDisabled = false;
                    } else if (status != 1 && status != 2 && status != 3) {
                        this.stat = 3;
                        this.isDisabled = true;
                    }
                });
                this.dialogTitle = this.stat == 1 ? '店外礼品调拨出库' : '店外礼品调拨入库'
                this.detail_dialog = true;
                getinfoList({ order_id: id, step: 'in' }).then(response => {
                    response.forEach(val => {
                        val.all_arrive = val.order_num == val.arrive_num ? true : false;
                    });
                    this.infolist = response;
                    this.count();
                    this.dialogLoading = false;
                });
            },
            // 计算
            count() {
                var totalPrice = 0; //临时总价
                var totalOrder = 0;
                this.infolist.forEach(function (val, index) {
                    totalPrice += val.order_num * 1 * val.money_cost * 1; //累计总价
                    totalOrder += val.order_num * 1;
                });
                this.totalPrice = parseFloat(totalPrice);
                this.totalOrder = parseFloat(totalOrder);
            },
            // 列表获取
            fetchData() {
                this.listLoading = true;
                this.currentPage = 1;
                getPage(this.formInline).then(response => {
                    this.totalDataNumber = response * 20;
                    getList(this.formInline).then(response => {
                        this.list = response;
                        this.listLoading = false;
                    });
                }).catch(res=>{
                    this.listLoading=false;
                });
            },
            // 分页
            handleCurrentChange(val) {
                this.listLoading = true;
                getList(this.formInline, val).then(response => {
                    this.list = response;
                    this.listLoading = false;
                });
            },
        }
    };
</script>